package com.ysxsoft.wdg.ui.activity.shopcart;

import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.cart.ShopcartBean;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.util.BigDecimalUtil;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.CART_upadata;


/**
 * 购物车
 */
public class ShopcartFragment extends BaseFragment implements OnRefreshListener {


    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_tv_r)
    TextView mEdit;
    @BindView(R.id.recyCart)
    RecyclerView recyCart;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.all_select)
    TextView mAllSelect;
    @BindView(R.id.sum_money_is)
    TextView mSumMoneyIs;
    @BindView(R.id.sum_money)
    TextView mSumMoney;
    @BindView(R.id.commit)
    TextView mCommit;


    private List<ShopcartBean> mList;
    private ShopcartAdapter mAdapter;

    private int page = 1, num = 1;
    private String uid = "",cardids = "", account = "";


    @Override
    protected void initData() {
        initStatusBar(topView, false);

        EventBus.getDefault().register(this);

        titleContent.setText("购物车");
        mEdit.setText(R.string.edit);

        uid = SharePrefUtils.getUserId();

        //购物车列表
        recyCart.setLayoutManager(new StaggeredGridLayoutManager(
                1, StaggeredGridLayoutManager.VERTICAL));
        mList = new ArrayList<>();
        mAdapter = new ShopcartAdapter(R.layout.item_shopcart);
        recyCart.setAdapter(mAdapter);

       onRefresh(refreshLayout);
    }


    private void postCart() {

        mApiHelper.getCartList(uid, new Observer<BaseBean<List<ShopcartBean>>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<List<ShopcartBean>> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    mList = baseBean.getData();
                    mAdapter.setNewData(mList);
                }else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void setListener() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setEnableLoadmore(false);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //                startActivity(new Intent(getContext(), GoodsDetailActivity.class)
                //                        .putExtra("gid",mList.get(position).getCid()));
            }
        });

        mAdapter.setOnItemSelectListener(new ShopcartAdapter.OnItemSelectListener() {
            @Override
            public void onItemSelect(int position) {
                List<ShopcartBean> data = mAdapter.getData();
                mList.get(position).setSelect(!mList.get(position).isSelect());
                mAdapter.notifyDataSetChanged();
                setBottomUI();
            }
        });

        mAdapter.setOnUpdateListener(new ShopcartAdapter.OnUpdateListener() {
            @Override
            public void onCountChange(int position, int num) {
                setBottomUI();
            }

            @Override
            public void onSkuClick(int position) {

            }

            @Override
            public void OnPriceChange() {
                setBottomUI();
            }
        });


    }

    private void setBottomUI() {
        mAllSelect.setSelected(ShopcartHelper.isAllSelect(mList));//刷新全选状态
        mCommit.setSelected(ShopcartHelper.hasSelect(mList));//刷新结算状态
        mAdapter.setDeleteMode(mEdit.isSelected());

        if (mEdit.isSelected()) {
            mEdit.setText(R.string.complete);
            mSumMoneyIs.setVisibility(View.GONE);
            mSumMoney.setVisibility(View.GONE);
            mCommit.setText(getString(R.string.delete));
        } else {
            mEdit.setText(R.string.edit);
            mSumMoneyIs.setVisibility(View.VISIBLE);
            mSumMoney.setVisibility(View.VISIBLE);
            account = BigDecimalUtil.formatDoubleScale(ShopcartHelper.getTotal(mList));
            num = ShopcartHelper.getSelectNum(mList);
            mSumMoney.setText(getString(R.string.price_rmb, account));//价格
            mCommit.setText(getString(R.string.settlement_num, num));
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_shopcar_new;
    }

    @OnClick({R.id.title_finish, R.id.title_tv_r, R.id.all_select, R.id.commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                getActivity().finish();
                break;
            case R.id.title_tv_r:
                mEdit.setSelected(!mEdit.isSelected());
                ShopcartHelper.setSelect(mList, false, true);
                mAdapter.notifyDataSetChanged();
                setBottomUI();
                break;

            case R.id.all_select:
                ShopcartHelper.setSelect(mList, !mAllSelect.isSelected(), false);
                mAdapter.notifyDataSetChanged();
                setBottomUI();
                break;

            case R.id.commit:
                List<Integer> selectCarIds = ShopcartHelper.getSelectCarIds(mList);
                cardids = new Gson().toJson(selectCarIds);
                if (selectCarIds.size() > 0)
                    if (mEdit.isSelected()) {
                        if (mCommit.isSelected()) {//删除订单
                            postDelete();
                        }
                    } else {
                        if (mCommit.isSelected()) {//提交订单
                            //getMorenAddress();
                         /*   Intent intent = new Intent(getContext(), ShopCartConfirmActivity.class);
                            intent.putExtra("account", account);
                            intent.putExtra("num", num);
                            intent.putExtra("cids", cardids);
                            startActivity(intent);*/

                         ShopcartConfirmActivity.start(mContext,cardids,num);
                        }
                    }
                break;
        }
    }


    private void postDelete() {
        mApiHelper.delCart(uid, cardids, new Observer<BaseBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean baseBean) {
                ToastUtils.showToast(baseBean.getMs());
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    ShopcartHelper.deleteSelectItem(mList);
                    mAdapter.setNewData(mList);
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast("请稍后再试");
            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
        ShopcartHelper.setSelect(mList, false, false);
        mAdapter.notifyDataSetChanged();
        setBottomUI();
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.finishRefresh(1000);
        mList.clear();
        mAdapter.clear();
        postCart();
    }


    @Subscribe
    public void getEvent(CommentEvent event) {
        if (event.getCode() == CART_upadata) {
            onRefresh(refreshLayout);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

}
